import { createRouter, createWebHashHistory, LocationQueryRaw } from 'vue-router';
import NProgress from 'nprogress';
import { useUserStore, useMenuStore, useConfigStore } from '@/store';
import 'nprogress/nprogress.css';
import PageLayout from '@/layout/page-layout.vue';
import { isLogin } from '@/utils/auth';
import Login from './modules/login';
import appRoutes from '@/router/routers';

NProgress.configure({ showSpinner: false });
const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    Login,
    {
      name: 'root',
      path: '/',
      component: PageLayout,
      children: appRoutes,
    },
    {
      path: '/',
      redirect: '/dashboard/workplace',
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'notFound',
      component: () => import('@/views/not-found/index.vue'),
    },
  ],
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    }
    return { top: 0, left: 0 };
  },
});

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  const userStore = useUserStore();
  const menuStore = useMenuStore();
  const configStore = useConfigStore();

  if (isLogin()) {
    try {
      if (menuStore.menus.length === 0) {
        await menuStore.getMenu();
        await configStore.initSiteConfig();
      }

      !menuStore.validateRoutePermission(to.name) ? next({ name: 'notFound' }) : next();

    } catch (error) {
      userStore.clearCache();
      next({
        name: 'login',
        query: { redirect: to.name, ...to.query, } as LocationQueryRaw,
      }
      );
    } finally {
      NProgress.done();
    }
  } else {
    if (to.name === 'login') {
      next();
      NProgress.done();
      return;
    }
    next({
      name: 'login',
      query: {
        redirect: to.name,
        ...to.query,
      } as LocationQueryRaw,
    });
    NProgress.done();
  }
});

export default router;
